package com.controller;

import com.entity.Play;
import com.service.PlayService;
import com.vo.PlayDetailVo;
import com.vo.PlayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PlayController {

    @Autowired
    private PlayService playService;


    @GetMapping("/seat")
    public String showSeats(@RequestParam String playId, Model model) {
        PlayDetailVo detailVo = playService.getDetailById(playId);
        model.addAttribute("detailVo", detailVo);
        return "seat";
    }

    @GetMapping("/slice")
    public String slice(Model model) {
        model.addAttribute("filmMap",playService.seleceFilm());
        model.addAttribute("roomMap",playService.seleceRomm());
        return "slice";
    }

    @PostMapping("/playInsert")
    public String playInsert(@RequestParam String filmid,@RequestParam String time,@RequestParam String lantype,
                             @RequestParam String roomid,@RequestParam String price,Model model){
        String msg = "排片失败";

        Random r = new Random();
        String id = "";
        for (int i=0;i<5;i++){
            id += r.nextInt(9);
        }
        id += time.substring(0,10).replace("-","");
        Play play = new Play();
        play.setpId(id);
        play.setfId(filmid);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            play.setpTime(format.parse(time.replace("T"," ")+":00"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        play.setLanType(lantype);
        play.setRoomId(roomid);
        play.setPrice(new BigDecimal(price));

        if(playService.playInsert(play) == 1){
            msg = "添加成功";
        }
        model.addAttribute("msg","layer.open({\n" +
                "                type: 0,\n" +
                "                content: '"+msg+"',\n" +
                "                offset:'t'\n" +
                "            });");
        return "slice";
    }

    @GetMapping("/playAll")
    @ResponseBody
    public Map<String,Object> palyAll(@RequestParam int page, @RequestParam int limit){

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "数据错误");
        map.put("count",playService.count() );
        map.put("data",playService.playAll(page*limit-limit,limit));
        return map;
    }

}
